//
//  XMUserDetailViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/19.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMUserDetailViewController.h"
#import "XMUserDetailBannerCell.h"
#import "XMUserDetailAboutTableViewCell.h"
#import "XMUserDetailTagsTableViewCell.h"
#import "XMUserDetailDescTableViewCell.h"
#import "XMUserDetailImgsTableViewCell.h"
#import "XMUserDetailBottomView.h"
#import "XMUserDetailMoreView.h"
#import "XMUserDetailRemarkView.h"
#import "XMLoginPrivacyTipView.h"
#import "XMUserDetailVoiceView.h"
#import "XMUserModel.h"

#import <SJVideoPlayer/SJVideoPlayer.h>
#import <NSAttributedString+SJMake.h>
#import <SJBaseVideoPlayer/SJBaseVideoPlayer.h>

#import "XMReportViewController.h"
#import "XMEditUserViewController.h"
#import "XMMyDynamicViewController.h"
#import "XMConversationViewController.h"
#import "XMRechargeViewController.h"


#import "XMAudioPlayer.h"
#import "XMHasGuardTipView.h"
#import "XMOpenGuardTipView.h"
#import "XMRCManager.h"
#import "XMCustomSendMessage.h"
#import "RCIM.h"

@interface XMUserDetailViewController ()

@property (nonatomic, strong) XMUserModel *userModel;
// 视频播放
@property (nonatomic, strong) SJVideoPlayer *player;
@property (nonatomic, assign) BOOL isPlaying;
@property (nonatomic, assign) BOOL myself;
@property (nonatomic, strong) XMUserDetailBottomView *bottomView;
@property (nonatomic, strong) XMUserDetailMoreView *moreView;
@property (nonatomic, strong) XMUserDetailRemarkView *remarkView;
@property (nonatomic, strong) XMLoginPrivacyTipView *blackView;
@property (nonatomic, strong) XMOpenGuardTipView *noGuardView;
@property (nonatomic, strong) XMHasGuardTipView *hasGuardView;

@end

@implementation XMUserDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
    [self userDetail];
    [self viewBlock];
    if (self.myself) {
        [kNotificationCenter addObserver:self selector:@selector(userDetail) name:@"photoListRefresh" object:nil];
    }
    
    [kNotificationCenter addObserver:self selector:@selector(userDetail) name:@"userDetailRefresh" object:nil];
}

- (BOOL)myself {
    return [XMUtil isBlankString:self.userId];
}

#pragma mark - initData
- (void)userDetail {
    NSMutableDictionary *dic = @{
        @"module": @"2"
    }.mutableCopy;
    if (![XMUtil isBlankString:self.userId]) {
        [dic setObject:self.userId forKey:@"see_user_id"];
    }
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            XMUserModel *userModel = [XMUserModel mj_objectWithKeyValues:result];
            self.userModel = userModel;
            [self.tableView reloadData];
            self.bottomView.model = userModel;
//            self.navTitleLa.text = [XMUtil isBlankString:userModel.alias] ? userModel.nickname : userModel.alias;
            if (![XMUtil isBlankString:userModel.video_cover.video_cover]) {
                [self.player.presentView.placeholderImageView sd_setImageWithURL:kStringToUrl(userModel.video_cover.video_cover)];
            }
            [self.moreView.blackButton setTitle:self.userModel.is_block ? @"取消拉黑" : @"拉黑" forState:UIControlStateNormal];
            
            if (!self.myself) {
                [[XMRCManager sharedInstance] updateUserCacheUserId:userModel.user_id alias:userModel.alias name:userModel.nickname portraitUri:userModel.avatar.file_url extra:[XMUtil extraJsonMember_time:userModel.member_time intimacy:userModel.intimacy]];
            }
        }
    }];
}

- (void)setupBlack {
    [MBProgressHUD showHUDActivityMsg:nil  toView:kWindow];
    NSMutableDictionary *dic = @{
        @"target_user_id": self.userModel.user_id
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/chat/blacklist/edit" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            if (self.userModel.is_block) {
                [MBProgressHUD showHUDSucc:@"取消拉黑成功" toView:kWindow];
                self.userModel.is_block = NO;
                [self.moreView.blackButton setTitle:@"拉黑" forState:UIControlStateNormal];
            } else {
                [MBProgressHUD showHUDSucc:@"拉黑成功" toView:kWindow];
                self.userModel.is_block = YES;
                [self.moreView.blackButton setTitle:@"取消拉黑" forState:UIControlStateNormal];
            }
        }
    }];
    
}

- (void)viewBlock {
    XMWeakSelf(self);
    self.bottomView.followBlock = ^(XMUserModel * _Nonnull model, UIButton * _Nonnull button) {
        XMStrongSelf(self);
        [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
        NSMutableDictionary *dic = @{
            @"target_user_id": self.userId
        }.mutableCopy;
        [YHNetworkManager.sharedInstance postWithUrl:@"api/chat/attention/edit" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                [MBProgressHUD hideHUD];
                self.userModel.is_regard = !self.userModel.is_regard;
                self.bottomView.model = self.userModel;
            }
        }];
    };
    
    self.bottomView.chatBlock = ^(XMUserModel * _Nonnull model, UIButton * _Nonnull button) {
        XMStrongSelf(self);
        if (self.fromChat) {
            [self backAction];
            return;
        }
        XMConversationViewController *conversationVC = [[XMConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:model.user_id];
        conversationVC.conversationType = ConversationType_PRIVATE;
        conversationVC.targetId = model.user_id;
        conversationVC.titleStr = model.showName;
        conversationVC.unReadMessage = 0;
        conversationVC.enableNewComingMessageIcon = YES; //开启消息提醒
        conversationVC.enableUnreadMessageIcon = YES;
        [self.navigationController pushViewController:conversationVC animated:YES];
    };
    
    self.remarkView.sureBlock = ^(NSString * _Nonnull str) {
        XMStrongSelf(self);
        [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
        NSMutableDictionary *dic = @{
            @"target_user_id": self.userId,
            @"remark": [NSString xm_stringNoNullWith:str]
        }.mutableCopy;
        [YHNetworkManager.sharedInstance postWithUrl:@"api/chat/userAlias/edit" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                [MBProgressHUD hideHUD];
                [GKCover hideCover];
                self.userModel.alias = str;
                [self.tableView reloadData];
            }
        }];
    };
    
    self.remarkView.closeBlock = ^{
        [GKCover hideCover];
    };
    
    self.noGuardView.guardBlock = ^{
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            [self openGuardData];
        }];
    };
    
    self.noGuardView.closeBlock = ^{
        [GKCover hideCover];

    };
    
    self.hasGuardView.guardBlock = ^{
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            [self openGuardData];
        }];
    };
    
    self.hasGuardView.closeBlock = ^{
        [GKCover hideCover];
    };
    
}

#pragma mark - 开守护
- (void)openGuardData {
    if (![self checkBalanceEnough:kGlobalVariables.appConfig.chat.user_guard_golds message:kGlobalVariables.appConfig.chat.otherMsgTipStr isGift:NO]) {
        return;
    }
    [MBProgressHUD showHUDActivityMsg:nil toView:kWindow];
    NSMutableDictionary *dic = @{
        @"target_user_id": self.userModel.user_id
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/chat/open/guard" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showHUDMsg:@"守护成功" toView:nil];
            kUserModel.golds = [result toString:@"user_golds"];
            XMCustomSendMessage *message = [XMCustomSendMessage guardMessageWithName:@"守护" golds:kGlobalVariables.appConfig.chat.user_guard_golds score:kStringFormat(@"%.2f", [result toFloat:@"give_score"]) msgType:@(2)];
            
            RCMessage *msg = [[RCMessage alloc] initWithType:(ConversationType_PRIVATE) targetId:self.userModel.user_id direction:MessageDirection_SEND content:message];
            
            [[RCIM sharedRCIM] sendMessage:msg
                               pushContent:nil
                                  pushData:nil
                              successBlock:^(RCMessage *successMessage) {
                
            } errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
            }];

        }
    }];
}

- (BOOL)checkBalanceEnough:(NSNumber *)price
                   message:(NSString *)message
                    isGift:(BOOL)isGift {
    if (isGift) {
        if (kUserModel.golds.integerValue < price.integerValue) {
            [XMAlertHelper alertTitle:@"金币不足"
                              message:message
                          cancelTitle:@"取消"
                            sureTitle:@"去充值"
                         cancelAction:nil
                           sureAction:^{
                [self toRecharge];
            }];
            return NO;
        }
    } else {
        if (kUserModel.golds.integerValue < price.integerValue && kUserModel.isMan) {
            [XMAlertHelper alertTitle:@"金币不足"
                              message:message
                          cancelTitle:@"取消"
                            sureTitle:@"去充值"
                         cancelAction:nil
                           sureAction:^{
                [self toRecharge];
            }];
            return NO;
        }
    }
    return YES;
}

- (void)toRecharge {
    XMRechargeViewController *vc = [[XMRechargeViewController alloc] initWithNibName:kStringFromClass(XMRechargeViewController) bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - setupSubviews
- (void)setupSubviews {
    [self.navLeftBtn setImage:kGetImage(@"xm_arrow_back") forState:UIControlStateNormal];
    self.navView.backgroundColor = kHEXA(@"FFFFFF", 0);
    self.navTitleLa.textColor = kHEXA(@"000000", 0);
    self.navRightBtn.adjustsImageWhenHighlighted = NO;
    if (self.myself) {
        [self.navRightBtn setImage:kGetImage(@"user_d_edit") forState:UIControlStateNormal];
        [self.navRightBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [self.navRightBtn setImagePosition:(XMImagePositionLeft) spacing:8];
        [self.navRightBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        self.navRightBtn.titleLabel.font = kUIFont(14);
        [self.navRightBtn setBackgroundColor:kAppMainColor];
        [self.navRightBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(80, 32));
        }];
        [self.navRightBtn addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];
        kCornerRadius(self.navRightBtn, 16, 0, UIColor.clearColor);
    } else {
        [self.navRightBtn setImage:kGetImage(@"user_d_more") forState:UIControlStateNormal];
        [self.navRightBtn addTarget:self action:@selector(more) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.view addSubview:self.bottomView];
    self.bottomView.hidden = self.myself;
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(self.myself ? 0 : 66);
        make.bottom.equalTo(self.view).offset(-kBottomSafeHeight);
    }];
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    
    [self tableViewRegisterNibWithNibName:kStringFromClass(XMUserDetailBannerCell)];
    [self tableViewRegisterNibWithNibName:kStringFromClass(XMUserDetailAboutTableViewCell)];
    [self tableViewRegisterNibWithNibName:kStringFromClass(XMUserDetailTagsTableViewCell)];
    [self tableViewRegisterNibWithNibName:kStringFromClass(XMUserDetailDescTableViewCell)];
    [self tableViewRegisterNibWithNibName:kStringFromClass(XMUserDetailImgsTableViewCell)];
    
    [self.view bringSubviewToFront:self.navView];
}

- (void)edit {
    XMEditUserViewController *vc = [[XMEditUserViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)more {
    [GKCover coverFrom:self.view contentView:self.moreView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
    
    XMWeakSelf(self);
    self.moreView.clickBlock = ^(XMUserDetailMoreType type) {
        XMLog(@"type%d", type);
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            switch (type) {
                case XMUserDetailMoreRemark:
                {
                    [self showRemarkView];
                }
                    break;
                case XMUserDetailMoreBlack:
                {
                    [self showBlackView];
                }
                    break;
                case XMUserDetailMoreReport:
                {
                    XMReportViewController *vc = [[XMReportViewController alloc] initWithNibName:kStringFromClass(XMReportViewController) bundle:nil];
                    vc.user_id = self.userModel.user_id;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
        }];
        
    };
}

- (void)showRemarkView {
    [GKCover coverFrom:self.view contentView:self.remarkView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
}

- (void)showBlackView {
    [GKCover coverFrom:self.view contentView:self.blackView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
    XMWeakSelf(self);
    [self.blackView tipViewLeftBlock:^{
        [GKCover hideCover];
    } rightBlock:^{
        XMStrongSelf(self);
        XMWeakSelf(self);
        [GKCover hideCoverWithHideBlock:^{
            XMStrongSelf(self);
            [self setupBlack];
        }];
    }];
}


#pragma mark - viewWillAppear
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.player vc_viewDidAppear];
    [self.player play];
    //    if (self.isFromLive) {
    //        /// 禁用侧滑返回
    //        if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    //            self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    //        }
    //    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.player vc_viewWillDisappear];
    [self.player pause];
    if ([XMAudioPlayer sharedInstance].isPlaying) {
        [[XMAudioPlayer sharedInstance] stopPlay];
    }
    //    if (self.isFromLive) {
    //        /// 激活侧滑返回
    //        if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    //            self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    //        };
    //    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.player vc_viewDidDisappear];
}

- (BOOL)prefersStatusBarHidden {
    return [self.player vc_prefersStatusBarHidden];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDarkContent;
//    return [self.player vc_preferredStatusBarStyle];
}

- (BOOL)prefersHomeIndicatorAutoHidden {
    return YES;
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.userModel.nickname.length > 0) {
        return [self.userModel userDetailCellHeightWithIndex:indexPath.row];
    }
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0: {
            XMUserDetailBannerCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMUserDetailBannerCell)];
            if (self.userModel.nickname.length > 0) {
                cell.model = self.userModel;
            }
            if (self.isPlaying && [self.userModel.video_cover.file_url length] > 0) {
                cell.isPlaying = self.isPlaying;
            }
            XMWeakSelf(self);
            cell.playBlock = ^(XMUserDetailBannerCell * _Nonnull cell, UIView * _Nonnull superView) {
                XMStrongSelf(self);
                self.isPlaying = YES;
                SJPlayModel *next = [SJPlayModel playModelWithTableView:self.tableView indexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                next.scrollViewSelector = @selector(collectionView);
                
                SJPlayModel *one = [SJPlayModel playModelWithCollectionView:cell.collectionView indexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
                one.superviewSelector = @selector(playerView);
                one.nextPlayModel = next;
                self.player.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:[NSURL URLWithString:self.userModel.video_cover.file_url] playModel:one];
            };
            
            cell.muteBlock = ^(UIButton * _Nonnull sender) {
                XMStrongSelf(self);
                self.player.muted = sender.selected;
            };
            
            cell.audioStartBlock = ^(XMUserDetailBannerCell * _Nonnull cell) {
                XMStrongSelf(self);
                if (self.isPlaying) {
                    [self.player pause];
                }
            };
            
            cell.audioEndBlock = ^(XMUserDetailBannerCell * _Nonnull bannerCell) {
                XMStrongSelf(self);
                if (self.player.isPaused) {
                    if (bannerCell.cIndex == 1) {
                        [bannerCell.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
                        
                    }
                    [self.player play];
                }
            };
            
            cell.guardBlock = ^{
                XMStrongSelf(self);
                self.hasGuardView.intimacyStr = self.userModel.intimacy;
                [GKCover coverFrom:self.view contentView:self.hasGuardView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleCenter) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:YES];
            };
            
            return cell;
        }break;
        case 1: {
            XMUserDetailAboutTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMUserDetailAboutTableViewCell)];
            if (self.userModel.nickname.length > 0) {
                cell.model = self.userModel;
            }
            XMWeakSelf(self);
            cell.moreBlock = ^(XMUserModel * _Nonnull model) {
                XMStrongSelf(self);
                XMMyDynamicViewController *vc = [[XMMyDynamicViewController alloc] init];
                vc.userId = model.user_id;
                vc.nickname = model.showName;
                vc.fromDetail = YES;
                [self.navigationController pushViewController:vc animated:YES];
            };
            return cell;
        }break;
        case 2: {
            XMUserDetailTagsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMUserDetailTagsTableViewCell)];
            if (self.userModel.nickname.length > 0) {
                [cell setupCellWithUser:self.userModel];
            }
            return cell;
        }break;
        case 3: {
            XMUserDetailDescTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMUserDetailDescTableViewCell)];
            if (self.userModel.nickname.length > 0) {
                cell.model = self.userModel;
            }
            return cell;
        }break;
        case 4: {
            XMUserDetailImgsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kStringFromClass(XMUserDetailImgsTableViewCell)];
            if (self.userModel.nickname.length > 0) {
                cell.model = self.userModel;
            }
            return cell;
        }break;
        default:
            return nil;
            break;
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    //    XMUserDetailBannerCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    //    SJPlayModel *next = [SJPlayModel playModelWithTableView:self.tableView indexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    //    next.scrollViewSelector = @selector(collectionView);
    //
    //    SJPlayModel *one = [SJPlayModel playModelWithCollectionView:cell.collectionView indexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    //    one.superviewSelector = @selector(playerView);
    //    one.nextPlayModel = next;
    //    self.player.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:[NSURL URLWithString:self.userModel.vedio] playModel:one];
    //    self.isPlaying = YES;
    //    [cell startPlay];
    //
    //    XMWeakSelf(self);
    //    cell.muteBlock = ^(UIButton * _Nonnull sender) {
    //        XMStrongSelf(self);
    //        self.player.muted = sender.selected;
    //    };
}

// 手动结束视频播放
- (void)endPlay {
    self.isPlaying = NO;
    XMUserDetailBannerCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0 ]];
    [cell endPlay];
    self.player = nil;
}

#pragma mark - 视频播放
- (void)viewSafeAreaInsetsDidChange {
    NSLog(@"A: %@", NSStringFromUIEdgeInsets(self.view.safeAreaInsets));
    [super viewSafeAreaInsetsDidChange];
}

- (void)_observePlayerViewAppearState {
    XMWeakSelf(self);
    self.player.playerViewWillAppearExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull videoPlayer) {
        NSLog(@"- playerViewWillAppear -");
        XMStrongSelf(self);
        self.isPlaying = YES;
        [self changeCellLocationLabelStatus];
    };
    
    self.player.playerViewWillDisappearExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull videoPlayer) {
        NSLog(@"- playerViewWillDisappear -");
        XMStrongSelf(self);
        self.isPlaying = NO;
        [self changeCellLocationLabelStatus];
    };
    self.player.playbackObserver.playbackDidFinishExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull player) {
        NSLog(@"- didPlayToEndTimeExeBlock -");
//        XMStrongSelf(self);
//        [self.player replay];
    };
}
- (void)changeCellLocationLabelStatus {
    XMUserDetailBannerCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (self.isPlaying && cell.cIndex == 0) {
        cell.locationLabel.hidden = YES;
        cell.playButton.hidden = YES;
    } else {
        cell.locationLabel.hidden = NO;
        cell.playButton.hidden = YES;
    }
    cell.locationLabel.text = [NSString stringWithFormat:@"%ld/%ld",cell.cIndex + 1, cell.dataArray.count];
}

#pragma mark - lazy
- (SJVideoPlayer *)player {
    if (_player == nil) {
        _player = [SJVideoPlayer player];
        _player.allowHorizontalTriggeringOfPanGesturesInCells = NO;
        _player.pausedWhenScrollDisappeared = NO;
        _player.resumePlaybackWhenScrollAppeared = NO;      // 滚动出现后, 如果暂停, 恢复播放
        _player.resumePlaybackWhenAppDidEnterForeground = NO;
        _player.smallViewFloatingController.enabled = NO;     // 开启小浮窗
        _player.gestureController.supportedGestureTypes = SJPlayerGestureTypeMask_None;
        _player.muted = YES;
        _player.autoplayWhenSetNewAsset = YES;
        _player.videoGravity = AVLayerVideoGravityResizeAspectFill;
        
        /*
         // top adapter items
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerTopItem_Back;             // 返回按钮
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerTopItem_Title;            // 标题
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerTopItem_PictureInPicture API_AVAILABLE(ios(14.0)); // 画中画item
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerTopItem_More;             // More


         // left adapter items
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerLeftItem_Lock;            // 锁屏按钮

         // right adapter items
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerRightItem_Clips;         // GIF/导出/截屏

         // bottom adapter items
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_Play;          // 播放按钮
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_CurrentTime;   // 当前时间
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_DurationTime;  // 全部时长
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_Separator;     // 时间分隔符(斜杠/)
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_Progress;      // 播放进度条
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_Full;          // 全屏按钮
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_LIVEText;      // 实时直播
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerBottomItem_Definition;    // 清晰度

         // center adapter items
         extern SJEdgeControlButtonItemTag const SJEdgeControlLayerCenterItem_Replay;
         */
        
        
        [_player.defaultEdgeControlLayer.topAdapter removeItemForTag:SJEdgeControlLayerTopItem_Back];
        [_player.defaultEdgeControlLayer.topAdapter removeItemForTag:SJEdgeControlLayerTopItem_Title];
        if (@available(iOS 14.0, *)) {
            [_player.defaultEdgeControlLayer.topAdapter removeItemForTag:SJEdgeControlLayerTopItem_PictureInPicture];
        }
        [_player.defaultEdgeControlLayer.topAdapter removeItemForTag:SJEdgeControlLayerTopItem_More];
        
        [_player.defaultEdgeControlLayer.leftAdapter removeItemForTag:SJEdgeControlLayerLeftItem_Lock];
        
        [_player.defaultEdgeControlLayer.rightAdapter removeItemForTag:SJEdgeControlLayerRightItem_Clips];
        
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Play];
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_CurrentTime];
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_DurationTime];
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Separator];
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Progress];
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Full];
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_LIVEText];
        [_player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Definition];
        
//        [_player.defaultEdgeControlLayer.centerAdapter removeItemForTag:SJEdgeControlLayerCenterItem_Replay];
        
        //        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 106)];
        //        view.backgroundColor = [UIColor clearColor];
        //
        //        UIButton *mutedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        [mutedBtn setTitle:@"🔇" forState:UIControlStateSelected];
        //        [mutedBtn setTitle:@"🔊" forState:UIControlStateNormal];
        //        mutedBtn.selected = YES;
        //        [mutedBtn addTarget:self action:@selector(mutedAction:) forControlEvents:UIControlEventTouchUpInside];
        //        mutedBtn.frame = CGRectMake(20, 0, 40, 40);
        //        [view addSubview:mutedBtn];
        //        SJEdgeControlButtonItem *item = [[SJEdgeControlButtonItem alloc] initWithCustomView:view tag:10086];
        //        [_player.defaultEdgeControlLayer.bottomAdapter addItem:item];
        //        [_player.defaultEdgeControlLayer.bottomAdapter reload];
        
        [_player.controlLayerAppearManager keepAppearState];
        _player.controlLayerAppearManager.disabled = YES;
        
        [self _observePlayerViewAppearState];
    }
    return _player;
}

- (void)mutedAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    _player.muted = sender.selected;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    float currentAlpha = (scrollView.contentOffset.y) / (float)(kScreenWidth / 2);
    self.navView.backgroundColor = kHEXA(@"ffffff", currentAlpha);
    self.navTitleLa.textColor = kHEXA(@"000000", currentAlpha);
//    if (currentAlpha > 0.25) {
//        [self.navLeftBtn setImage:kGetImage(@"xm_arrow_back") forState:UIControlStateNormal];
//    } else {
//        [self.navLeftBtn setImage:kGetImage(@"xm_arrow_back") forState:UIControlStateNormal];
//    }
}

- (XMUserModel *)userModel {
    if (_userModel == nil) {
        _userModel = [[XMUserModel alloc] init];
    }
    return _userModel;
}

- (XMUserDetailBottomView *)bottomView {
    if (_bottomView == nil) {
        _bottomView = [XMUserDetailBottomView viewFromXib];
    }
    return _bottomView;
}

- (XMUserDetailMoreView *)moreView {
    if (_moreView == nil) {
        _moreView = [XMUserDetailMoreView viewFromXib];
        _moreView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _moreView;
}

- (XMUserDetailRemarkView *)remarkView {
    if (_remarkView == nil) {
        _remarkView = [XMUserDetailRemarkView viewFromXib];
        _remarkView.type = XMEditUserInputTypeRemark;
        _remarkView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _remarkView;
}

- (XMLoginPrivacyTipView *)blackView {
    if (_blackView == nil) {
        _blackView = [XMLoginPrivacyTipView viewFromXib];
        _blackView.size = CGSizeMake(295, 177);
        [_blackView setupCommonTitle:@"温馨提示" content:@"加入黑名单后，你将不再收到对方的消息，同时删除与该联系人的聊天记录！"];
    }
    return _blackView;
}

- (XMOpenGuardTipView *)noGuardView {
    if (_noGuardView == nil) {
        _noGuardView = [XMOpenGuardTipView viewFromXib];
        _noGuardView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _noGuardView;
}

- (XMHasGuardTipView *)hasGuardView {
    if (_hasGuardView == nil) {
        _hasGuardView = [XMHasGuardTipView viewFromXib];
        _hasGuardView.size = CGSizeMake(kScreenWidth, kScreenHeight);
    }
    return _hasGuardView;
}

- (void)dealloc {
    [kNotificationCenter removeObserver:self];
}

@end
